package com.wavecoler.professor.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.wavecoler.professor.objects.Course;
import com.wavecoler.professor.objects.Problem;

@SuppressWarnings("serial")
public class ShowCourse extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = req.getParameter("course");
		
		HttpSession session = req.getSession();
		@SuppressWarnings("unchecked")
		ArrayList<Course> coursillos =  (ArrayList<Course>) session.getAttribute("cursos");
		
		String idcurso = null;
		
		for(int i = 0; i < coursillos.size();i++){
			if(name.equals(coursillos.get(i).getCourseName())){
				idcurso = coursillos.get(i).getCourseId();
				break;
			}
		}
		
		ArrayList<Problem> problemas = new ArrayList<Problem>();

		Client anotherService = Client.create();
		WebResource webResourcetwo = anotherService.resource("http://wavecoler.lag.itesm.mx:8080/WaveColerWebServices/rest/problems/course/"+idcurso+"");
		ClientResponse respuestados = webResourcetwo.accept("application/json").get(ClientResponse.class);
		final JSONObject jsonObjecti = respuestados.getEntity(JSONObject.class);	
	System.out.println(jsonObjecti.toString());
		try {
			//Hay que checar, pues si nada mas es un solo problema, el json no nos regresara un arreglo, si no un simple objeto en json
			JSONArray ble = jsonObjecti.getJSONArray("problem");
			
			for(int i = 0; i < ble.length();i++){
				JSONObject bli = ble.getJSONObject(i);
				Gson gsons = new Gson();
				BufferedReader brs = new BufferedReader(new StringReader(bli.toString()));
				Problem problem = gsons.fromJson(bli.toString(), Problem.class);
				System.out.println(problem.getProblemId());
				problemas.add(problem);
			}
			
			for(int i = 0; i < problemas.size();i++){
				System.out.println("Se agrego: " + problemas.get(i).getName());
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		session.setAttribute("problems", problemas);
		session.setAttribute("coursename",name);
		String address = "jsps/Course.jsp";
	    RequestDispatcher dispatcher = req.getRequestDispatcher(address);
	    dispatcher.forward(req, resp);
		
	}

}
